package com.kingstar.ceres.data.load;

import com.kingstar.ceres.data.bo.BaseFileMapping;
import com.kingstar.ceres.data.constant.FileImportConstants;
import com.kingstar.ceres.data.properties.FileMappingProperties;
import com.kingstar.ceres.data.util.FileImportUtils;
import com.kingstar.ceres.data.util.FormatUtils;
import com.kingstar.ceres.data.util.XmlUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class FileMappingResourceLoad implements ResourceLoad{

    private final static String resourceLocation="classpath:fileMapping.xml";

    @Override
    public List<? extends BaseFileMapping> loadConfig(List<String> fileIds, String fileType, String batchPath) throws Exception {
        log.info("get file mapping:{},fileIds:{}",fileType,fileIds);
        List<? extends BaseFileMapping>  list=null;
        if (FileImportConstants.FILE_TYPE_CSV.equals(fileType)){
            list= XmlUtil.xmlMapper
                    .readValue(ResourceUtils.getFile(resourceLocation), FileMappingProperties.class)
                    .getCsvFileMapping();
        }
        if (FileImportConstants.FILE_TYPE_EXCEL.equals(fileType)){
            list= XmlUtil.xmlMapper
                    .readValue(ResourceUtils.getFile(resourceLocation), FileMappingProperties.class)
                    .getExcelFileMapping();
        }
        if(list==null){
            throw new RuntimeException("未知的文件类型"+fileType);
        }
        log.info("fileMapping:{}",list);
        if (CollectionUtils.isEmpty(fileIds)){
            dealFilePath(list,batchPath);
            return list;
        }

        List<? extends BaseFileMapping> result = list.stream().
                filter(v -> fileIds.contains(v.getFileId()))
                .collect(Collectors.toList());
        dealFilePath(result,batchPath);
        log.info("matching fileMapping:{}",result);
        return result;
    }

    private static void dealFilePath(List<? extends BaseFileMapping> list,String batchPath){
        for (BaseFileMapping baseFileMapping : list) {
            String fileName = baseFileMapping.getFileName();
            String localPath = (String) ElUtil.resolverExpression(baseFileMapping.getLocalPath());
            baseFileMapping.setFileName(FormatUtils.parseBody(fileName));
            if(StringUtils.isNotBlank(baseFileMapping.getRemotePath())){
                String remotePath = (String) ElUtil.resolverExpression(baseFileMapping.getRemotePath());
                baseFileMapping.setRemotePath(FileImportUtils.parseParentDir(remotePath,batchPath));
            }
            baseFileMapping.setLocalPath(FileImportUtils.parseParentDir(localPath,batchPath));
        }
    }
}
